package com.darrenchan.leetcode;

import java.util.Arrays;

/**
 * @Desc
 * @Author chenchi03
 * @CreateTime 2020-01-22 20:27
 * 还原路径，把路径打出来
 */
public class Q300 {
    public int lengthOfLIS(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }

        int len = nums.length;
        int[] dp = new int[len];
        int[] pi = new int[len];
        int max = 0;
        int last = 0;

        for (int i = 0; i < len; i++) {
            dp[i] = 1;
            pi[i] = -1;
            for (int j = 0; j < i; j++) {
                if (nums[i] > nums[j]) {
                    dp[i] = Math.max(dp[i], dp[j] + 1);
                    if (dp[i] == dp[j] + 1) {
                        pi[i] = j;
                    }
                }
            }
            if (max < dp[i]) {
                max = dp[i];
                last = i;
            }
        }

        int[] path = new int[max];
        for (int i = 0; i < max; i++) {
            path[max - 1 - i] = nums[last];
            last = pi[last];
        }

        System.out.println(Arrays.toString(path));

        return max;
    }

    /**
     * nlogn解法
     *
     * @param nums
     * @return
     */
    public int lengthOfLIS2(int[] nums) {
        if (nums == null || nums.length == 0) {
            return 0;
        }

        int len = nums.length;
        //b[i] means the minimum nums[x] when f[x]=i
        int[] b = new int[len + 1];
        b[0] = Integer.MIN_VALUE;
        int top = 0, j = 0;
        for (int i = 0; i < len; i++) {
            int start = 0;
            int end = top;
            while (start <= end) {
                int mid = start + (end - start) / 2;
                if (b[mid] < nums[i]) {
                    start = mid + 1;
                    j = mid;
                } else {
                    end = mid - 1;
                }
            }
            b[j + 1] = nums[i];
            if (top < j + 1) {
                top = j + 1;
            }
        }

        //b[0], b[1], ..., b[top]
        return top;
    }

    public static void main(String[] args) {
        System.out.println(new Q300().lengthOfLIS(new int[]{10, 9, 2, 5, 3, 7, 101, 18}));
    }
}
